#!/usr/bin/ruby
$:.unshift File.join(File.dirname(__FILE__))
require 'AWS/EC2'
require 'basic_configuration'
require 'aws_context'
require 'pp'

# List all images.
# It takes a while, so be patient.
# If a pattern is supplied, it is used to filter the output.

if ARGV[0] == '-?'
  puts "usage: list-images [pattern]"
  exit 1
end

if ARGV.size > 0 then
  filter=Regexp.new(ARGV[0])
else
  filter=Regexp.new('.*')
end

Signal.trap("INT") do
  exit 2
end

config = BasicConfiguration.new
ec2 = AwsContext.instance.ec2(*config.keys)
begin
  images = ec2.describe_images
  #pp images
  images.each do |i|
    if i[:location] =~ filter
      puts "#{i[:id]} #{i[:location]}"
    end
  end
rescue
  puts "error #{$!}"
  exit 1
end
